import React, { useMemo, useRef } from "react";
import { Button, Popconfirm } from "antd";

import { ProTable, type TableType, type IProTableRef } from "@yaf/pro-ui";
import { useThemeToken } from "@/constants";
import { AuthCan, EnumAuthKey } from "@/service";

import { getDataAction, filterItems } from './proTableDriver';
import { RespDataType, deleteOnlineUser } from '../api';

const List: React.FC = () => {
  const { themeToken } = useThemeToken();
  const proTableRef = useRef<IProTableRef>();
  const columns = useMemo(() => getColumns(), []);

  return <ProTable
    ref={proTableRef}
    dataAction={getDataAction(proTableRef)}
    rowKey={"id"}
    theme={themeToken.proTableToken}
    headerProps={{
      operatorProps: {
        btnList: [],
      },
      filterProps: {
        maxWidth: "60%",
        filterItems
      }
    }}
    contentProps={{
      isShowRowSelection: false,
      tableProps: {
        columns,
      }
    }}
    onError={(msg) => console.error(msg)}
  />
}

export default List;

const getColumns = () => {
  const columns: TableType.ColumnsType<RespDataType.OnlineUserItem> = [
    {
      title: '会话编号',
      dataIndex: 'uuid',
    },
    {
      title: '登录名称',
      dataIndex: 'userName',
    },
    {
      title: '主机',
      dataIndex: 'ip',
    },
    {
      title: '浏览器',
      dataIndex: 'explorer',
    },
    {
      title: '操作系统',
      dataIndex: 'os',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render: (_, record) => {
        return <Popconfirm
          title="确定强制退出"
          onConfirm={() => deleteOnlineUser([record.id]).catch(e => e)}
        >
          <AuthCan authKey={EnumAuthKey.sysOnlineUser.forceLogoutButton}>
            <Button size="small" danger>强制退出</Button>
          </AuthCan>
        </Popconfirm>
      }
    },
  ];

  return columns;
}
